package com.hog.utils;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 *
 * @author 唐晴
 * @version v1.0
 * @date 2017/10/23 16:43
 * @since JDK1.8
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    /**
     * 若OBJ为null, 返回""; 否则返回OBJ.toString();
     *
     * @param obj
     * @return 若OBJ为null, 返回""; 否则返回OBJ.toString();
     */
    public static String emptyIfNull(Object obj) {
        return obj == null ? "" : obj.toString();
    }

    /**
     * 是否所允许的文件类型
     *
     * @param filename 文件名
     * @param suffixs  后缀数组参数
     * @return boolean
     */
    public static boolean allowedFile(String filename, String... suffixs) {
        if (null == suffixs || suffixs.length == 0) {
            return true;
        }
        String fileExt = filename.substring(filename.lastIndexOf(".") + 1);
        boolean res = false;
        for (String s : suffixs) {
            if (fileExt.equalsIgnoreCase(s)) {
                res = true;
            }
        }
        return res;
    }

    /**
     * 解析单个位号按","分隔的的位号区域 (可能包含'-', 或许不包含),
     * 2014-4-14:部分从雷哥那里copy过来的;
     *
     * @param refDes
     * @return Set<String>
     */
    public static Set<String> parseEachRefDes(String refDes) {
        Set<String> refDescs = new HashSet<>();
        if (isEmpty(refDes)) {
            return refDescs;
        }
        if (!refDes.contains("-")) {
            // 若每个按逗号分割的位号不包含"-"符号
            refDescs.add(refDes);
        } else {
            Pattern pattern = Pattern.compile("^([A-Za-z]*)([0-9]*)-([A-Za-z]*)([0-9]*)$");
            Matcher matcher = pattern.matcher(refDes);
            boolean result = matcher.find();
            if (!result) {//如果没找到
                refDescs.add(refDes);
            } else if (matcher.groupCount() != 4) {//如果找到的与格式C10-C20不符合
                refDescs.add(refDes);
            } else {
                try {//C1-C5 => C1,C2,C3,C4,C5
                    String prefix1 = matcher.group(1);
                    String prefix2 = matcher.group(3);
                    int iStart = Integer.parseInt(matcher.group(2));
                    int iEnd = Integer.parseInt(matcher.group(4));
                    if (!prefix1.equals(prefix2)) {
                        refDescs.add(refDes);
                    }
                    if (iStart >= iEnd) {
                        refDescs.add(refDes);
                    }
                    for (int i = iStart; i <= iEnd; i++) {
                        String ref = prefix1 + "" + i;
                        refDescs.add(ref);
                    }
                } catch (Exception e) {
                    refDescs.add(refDes);
                    e.printStackTrace();
                }

            }
        }
        return refDescs;
    }

    /**
     * 解析位号字符串成Set集合
     *
     * @param refDes 位号字符串：RB110,RB810,RB812
     * @return Set<String>
     */
    public static Set<String> parseRefDes(String refDes) {
        Set<String> refDescs = new HashSet<>();
        if (isEmpty(refDes)) {
            return refDescs;
        }
        for (String ref : refDes.split("\\s*,\\s*")) {
            refDescs.addAll(parseEachRefDes(ref));
        }
        return refDescs;
    }

    /**
     * 拼接位号
     *
     * @param src 旧位号
     * @param add 追加位号
     * @return 新位号
     */
    public static String addRefDes(String src, String add) {
        Set<String> srcSet = parseRefDes(src);
        Set<String> addSet = parseRefDes(add);
        srcSet.addAll(addSet);
        return specJoin(srcSet, ",");
    }

    /**
     * 获取删除后的BOM加工参数，BOM加工描述
     *
     * @param procSpec       原BOM加工参数，BOM加工描述
     * @param deledFtNumList 删除位号列表
     * @return 新BOM加工参数，BOM加工描述
     */
    public static String updateProcSpec(String procSpec, Collection<String> deledFtNumList) {

        List<String> list = new ArrayList<>();
        Collections.addAll(list, procSpec.split("\\s*;\\s*"));
        List<String> delList = new ArrayList<>();
        for (String l : list) {
            for (String ftNum : deledFtNumList) {
                if (l.contains(ftNum)) {
                    delList.add(l);
                }
            }
        }
        list.removeAll(delList);

        String updatedSpec = specJoin(list, ";");//StringUtils.join(list, ";").replaceAll(";+", ";").replaceAll("(^;+)|(;+$)", "");
        return updatedSpec;
    }

    /**
     * 将列表通过分隔符拼接成字符串，过滤掉头尾等非必要拼接
     *
     * @param list  待拼接列表
     * @param spilt 拼接分隔符
     * @return 拼接后字符串
     */
    public static String specJoin(Collection<String> list, String spilt) {
        String spec = StringUtils.join(list, spilt).replaceAll(spilt + "+", spilt).replaceAll("(^" + spilt + "+)|(" + spilt + "+$)", "");
        return spec;
    }

    /**
     * 格式化百分比
     *
     * @param sub  分子
     * @param main 分母
     * @param digs 保留小数点位数
     * @return 百分比格式字符串
     */
    public static String formatePercent(int sub, int main, int digs) {
        NumberFormat format = NumberFormat.getPercentInstance();
        format.setMinimumFractionDigits(digs);
        return format.format((double) sub / (double) main);
    }

    /**
     * 去掉前后半角全角空格
     *
     * @param str 原字符串
     * @return 去首尾空格后字符串
     */
    public static String trims(String str) {
        if (null == str || str.isEmpty()) {
            return "";
        }
        char[] value = str.toCharArray();
        int len = value.length;
        int st = 0;
        char[] val = value;    /* avoid getfield opcode */
        while ((st < len) && (val[st] <= ' ' || val[st] == '　' || ' ' == val[st])) {
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ' || val[len - 1] == '　' || ' ' == val[len - 1])) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ? str.substring(st, len) : str;
    }

    /**
     * 合并不同字符串分隔符下相同部分
     *
     * @param spilt   分隔符
     * @param first   字符串一
     * @param seconds 待合并字符串数组
     * @return 合并后字符串
     */
    public static String mergeStr(String spilt, String first, String... seconds) {
        Set<String> msg = new HashSet<>();
        if (null != first && isNotEmpty(first)) {
            for (String f : first.split(spilt)) {
                msg.add(f);
            }
        }
        if (null != seconds && seconds.length > 0) {
            for (String second : seconds) {
                if (null != second && isNotEmpty(second)) {
                    for (String s : second.split(spilt)) {
                        msg.add(s);
                    }
                }
            }
        }
        return join(msg, spilt);
    }

    /**
     * 按字节截取字符串
     *
     * @param str
     * @param bytes
     * @return
     */
    public static String subStringByBytes(String str, int bytes) {
        if (str == null || str.length() == 0) {
            return str;
        }
        int len = 0;
        for (int i = 0; i < str.length(); i++) {
            //GBK 编码格式 中文占两个字节 UTF-8 编码格式中文占三个字节;
            len += (str.charAt(i) > 255 ? 3 : 1);
            if (len > bytes) {
                return str.substring(0, i);
            }
        }
        return str;
    }

    /**
     * 判断对象是否为空
     *
     * @param object
     * @return
     */
    public static boolean isBlank(Object object) {
        if (object == null) {
            return true;
        }
        return isBlank(object.toString());
    }

    /**
     * 去除首尾指定字符
     *
     * @param str     字符串
     * @param element 指定字符
     * @return 去掉指定字符的字符串
     * @author chenyimin
     */
    public static String trimFirstAndLastChar(String str, String element) {
        if (StringUtils.isBlank(str)) {
            return str;
        }
        boolean beginIndexFlag = true;
        boolean endIndexFlag = true;
        do {
            int beginIndex = str.indexOf(element) == 0 ? 1 : 0;
            int endIndex = str.lastIndexOf(element) + 1 == str.length() ? str.lastIndexOf(element) : str.length();
            str = str.substring(beginIndex, endIndex);
            beginIndexFlag = (str.indexOf(element) == 0);
            endIndexFlag = (str.lastIndexOf(element) + 1 == str.length());
        } while (beginIndexFlag || endIndexFlag);
        return str;
    }

    public static void main(String[] args) {
        System.out.println(parseRefDes("TP-MPT"));
    }

    public static String stripHtml(String content) {
        // <p>段落替换为换行
        content = content.replaceAll("<p .*?>", "");
        // <br><br/>替换为换行
        content = content.replaceAll("<br\\s*/?>", "");
        // 去掉其它的<>之间的东西
        content = content.replaceAll("\\<.*?>", "");
        return content;
    }
}
